<?php

namespace app\admin\controller;

use app\api\controller\Pay;
use app\common\controller\admin\Base;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

class Payconfig extends Base
{


    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\PayConfig;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $adminId = $this->request->post('admin_id', '');
            $switch = $this->request->post('switch', '');
            $country_config_id = $this->request->post('country_config_id', '');
            if ($country_config_id != '') {
                $where['country_config_id'] = $country_config_id;
            }
            if ($adminId != '') {
                $where['admin_id'] = $adminId;
            }
            if ($switch != '') {
                $where['switch'] = $switch;
            }

            $where['is_del'] = 0;
            $list = $this->model
                ->field('id,title,nickname,switch,is_default,create_time,point_position,channel_code,configjson,other_information,country_config_id')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select();
            $countryConfigList = \app\admin\model\CountryConfig::select()->toArray();
            $countryConfigList = array_column($countryConfigList, null, 'id');
            foreach ($list as $key => $value) {
                $value['configjson'] = unserialize($value['configjson']);

                $value['country_name'] = empty($countryConfigList[$value['country_config_id']]) ? '' : $countryConfigList[$value['country_config_id']]['name'];
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $params['configjson'] = serialize($params['configjson']);
//                    if ($params['is_default'] == 1) {
//                        $oldwhere['is_default'] = 1;
//                        $this->model->update(['is_default' => 0], $oldwhere);
//                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    $params['configjson'] = serialize($params['configjson']);
                    $result = $row->allowField(true)->isUpdate(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 详情
     */
    public function details($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('未查询到数据！', '', '', 404);
        }
        $row['configjson'] = unserialize($row['configjson']);
        $this->success('详情数据', '', $row);
    }

    //生成测试支付链接
    public function getTestPayUrl($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('未查询到数据！', '', '', 404);
        }
        $list = [];
        $payConfigKey = unserialize($row['configjson']);
        $payConfigKey = json_decode($payConfigKey, true);
        //生成5000的支付链接
        $amount_money = 5000;
        $resData = $this->createPayUrl($payConfigKey, $row, $amount_money);
        $list[] = [
            'name' => '5000',
            'pay_url' => empty($resData['payurl']) ? '' : $resData['payurl'],
            'msg' => empty($resData['payurl']) ? $resData['msg'] : ''
        ];
        //生成15000的支付链接
        $amount_money = 15000;
        $resData = $this->createPayUrl($payConfigKey, $row, $amount_money);

        $list[] = [
            'name' => '15000',
            'pay_url' => empty($resData['payurl']) ? '' : $resData['payurl'],
            'msg' => empty($resData['payurl']) ? $resData['msg'] : ''
        ];
        //生成55000的支付链接
        $amount_money = 55000;
        $resData = $this->createPayUrl($payConfigKey, $row, $amount_money);

        $list[] = [
            'name' => '55000',
            'pay_url' => empty($resData['payurl']) ? '' : $resData['payurl'],
            'msg' => empty($resData['payurl']) ? $resData['msg'] : ''
        ];
        $this->success('获取成功!', '', $list);
    }

    private function createPayUrl($payConfigKey, $info, $amount_money)
    {
        //生成一条支付链接
        $out_trade_no = createTradeNo();
        $payUrl = new Pay();
        //各种通道需要什么字段持续做增量
        $createPayUrlData = [
            'out_trade_no' => $out_trade_no,
            'amount_money' => $amount_money,
            'user_id' => 0,
            'user_name' => 'test',
            'user_email' => '',
            'user_phone' => '9582473827',
        ];
        $payConfigKey = array_values($payConfigKey)[0];
        $payUrlRes = $payUrl->getPayUrl($payConfigKey['appId'], $payConfigKey['appKey'], $info['nickname'], $createPayUrlData);
        if (empty($payUrlRes['payurl'])) {
            //记录错误日志
            Log::error(json_encode($payUrlRes));
//            $this->error('支付链接生成失败!');
            if (empty($payUrlRes['msg'])) {
                $payUrlRes['msg'] = '支付链接生成失败!';
            }
        }
        return $payUrlRes;
    }
}
